import unittest

from app import app
from model import db
from model.crud import UpdateInstance, QueryOneInstance, DeleteInstance, QueryPaginatedPosts
from model.tables import Blog


class UtilsTestCase(unittest.TestCase):

    def setUp(self):
        self.app = app  # 你项目中的测试配置
        self.app_context = self.app.app_context()
        self.app_context.push()
        db.create_all()

    def tearDown(self):
        db.session.remove()
        db.drop_all()
        self.app_context.pop()

    def test_update_and_query_instance(self):
        blog = Blog(title="Test", content="Original",uid=1)
        UpdateInstance(blog)

        queried = QueryOneInstance(Blog, {"title": "Test"})
        self.assertIsNotNone(queried)
        self.assertEqual(queried.content, "Original")

        # 修改内容
        UpdateInstance(queried, {"content": "Updated"})
        self.assertEqual(queried.content, "Updated")

    def test_delete_instance(self):
        blog = Blog(title="Delete Me", content="bye")
        UpdateInstance(blog)

        queried = QueryOneInstance(Blog, {"title": "Delete Me"})
        self.assertIsNotNone(queried)

        DeleteInstance(queried)
        deleted = QueryOneInstance(Blog, {"title": "Delete Me"})
        self.assertFalse(deleted)  # 或用 assertEqual(deleted, NULL_OBJECT) 看你代码逻辑

    def test_query_paginated_posts(self):
        for i in range(15):
            blog = Blog(title=f"Post {i+1}", content="...", checked=True, passed=True)
            UpdateInstance(blog)

        query = Blog.query.filter_by(checked=True, passed=True)

        # 第一次分页
        blogs, offset = QueryPaginatedPosts(query, limit=10, asc=True)
        self.assertEqual(len(blogs), 10)
        self.assertEqual(blogs[0].title, "Post 1")

        # 第二次分页
        blogs2, offset2 = QueryPaginatedPosts(query, limit=10, asc=True, offset=offset)
        self.assertEqual(len(blogs2), 5)
        self.assertEqual(blogs2[0].title, "Post 11")


if __name__ == '__main__':
    unittest.main()
